#include <sys/types.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <sstream>
#include "CKDistributed.h"



namespace K_Engine
{
	CKDistributed::CKDistributed() : 
		m_sock(0),
		m_right(false),
		m_strLastError("")
	{
	}
	
	
	CKDistributed::~CKDistributed()
	{	
	}
	
	
	std::string CKDistributed::strGetLastError()
	{
		if(!m_right)
			return m_strLastError;
		else
			return "";
	}
	
	
	void CKDistributed::SetLastError(std::string _strlasterror)
	{
		m_strLastError = _strlasterror;
	}
		
	
	bool CKDistributed::init(std::string address, int port)
	{
		struct sockaddr_in addr;
		addr.sin_family = AF_INET;
		addr.sin_port = port;
		addr.sin_addr.s_addr = inet_addr(address.c_str());
		
		if(( m_sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
		{
			m_right = false;
			SetLastError("在CKMsgLoop中初始化socket错误");
			return false;
		}
		if( bind(m_sock, (struct sockaddr*)&addr, sizeof(addr)) < 0 )
		{
			m_right = false;
			std::stringstream err;
			err<<"在CKMsgLoop中绑定端口"<<port<<"失败";
			SetLastError(err.str());
			return false;
		}
		m_right = true;
		return true;
	}
}
